//
//  NestedScrollView.swift
//  Utility
//
//  Created by 于虎拴 on 2022/10/27.
//

import Foundation
import UIKit

public class NestedScrollView: UIScrollView, UIScrollViewDelegate {
  public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)
//    print("touchesMoved")
  }
  
  public override init(frame: CGRect) {
    super.init(frame: frame)
    
//    addGestureRecognizer(nestedPanGestureRecognizer)
    delegate = self
  }
  
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  /// 通过手势实现滑动
  private lazy var nestedPanGestureRecognizer: UIPanGestureRecognizer = {
    return UIPanGestureRecognizer(target: self, action: #selector(panPiece(_:)))
  }()
  
  var initialOffset = CGPoint()
  var maxOffsetY = CGFloat.zero
  @objc private func panPiece(_ gestureRecognizer: UIPanGestureRecognizer) {
    guard let piece = gestureRecognizer.view else { return }
    // 获取相对于父视图坐标空间的 X 和 Y 方向的变化。
    let translation = gestureRecognizer.translation(in: piece.superview)
    switch gestureRecognizer.state {
    case .began:
      // 保存原始位置。
      initialOffset = contentOffset
      maxOffsetY = contentSize.height - bounds.height
    case .changed, .ended: // 更新 .began、.changed 和 .ended 状态的位置
      let newOffsetY = initialOffset.y - translation.y
      let offsetY = min(max(0, newOffsetY), maxOffsetY)
      self.contentOffset = CGPoint(x: 0, y: offsetY)
    default:
      break
    }
  }
  
  public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    print(#function)
  }
}

extension NestedScrollView: UIGestureRecognizerDelegate {
  /// 实现手势穿透的关键代码
  ///
  /// 返回 true 允许两者同时识别。默认实现返回 false（默认情况下不能同时识别两个手势）
  public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    if gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) {
      if gestureRecognizer.state == .began {
        print("gestureRecognizer.view", gestureRecognizer.view)
      }
    }
    
    if otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self) {
      if otherGestureRecognizer.state == .began {
        print("otherGestureRecognizer.view", otherGestureRecognizer.view)
        if let piece = otherGestureRecognizer.view {
          let translation = (otherGestureRecognizer as! UIPanGestureRecognizer).translation(in: piece.superview)
          print("translation:", translation)
          if translation.y > 0 { // 下拉
            return false
          }
        }
      }
    }
//    guard let scrollView = otherGestureRecognizer.view as? UIScrollView else { return false }
//
//    guard scrollView != self else { return false }
//
//    print("gestureRecognizer:", gestureRecognizer)
//    print("otherGestureRecognizer:", otherGestureRecognizer)
    print("")
//    print("otherGestureRecognizer.view:", otherGestureRecognizer.view)
//    print("otherGestureRecognizer.state", otherGestureRecognizer.state.rawValue)
    return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
  }
}
